<?php
	$_SESSION['site'] = array('menu', 'newsletter');

    postNewsletterButtonLeiste ();

    if (isset($_POST['speichernNewsletter'])) {
        if ($_POST['id']) {
            $query = mysql_query('UPDATE Newsletter set Betreff="' . $_POST['betreff'] . '", Text="' . $_POST['text'] . '", Aktiv=' . $_POST['aktiv'] . ' where ID=' . $_POST['id']);
            
            if ($query) {
                echo "<div class='info'>Newsletter erfolgreich ge&auml;ndert!</div>";
                postNewsletterListe ();
                // TODO: Fehlerbehandlung
            } else {
                echo "<div class='error'>Newsletter konnte nicht ge&auml;ndert werden!</div>";
            }
        } else {
            $query = mysql_query('INSERT into Newsletter values (null,"' . $_POST['text'] . '", "' . $_POST['betreff'] . '", null, ' . $_POST['aktiv'] . ')');
            if ($query) {
                echo "<div class='info'>Newsletter erfolgreich angelegt!</div>";
                postNewsletterListe ();
                // TODO: Fehlerbehandlung
            } else {
                echo "<div class='error'>Newsletter konnte nicht angelegt werden!</div>";
                postNewsletterListe ();
            }
        }

    } elseif (isset($_POST['neuerNewsletter'])) {
        postNewsletter (array());

    } elseif (isset($_POST['detailsNewsletter'])) {
        $newsletter = $_POST['detailsNewsletter'];
        postDetailsNewsletter ($newsletter);

    } elseif (isset($_POST['versendenNewsletter'])) {
        $newsletterid = $_POST['versendenNewsletter'];
        sendNewsletter ($newsletterid);

    } elseif (isset($_POST['abonnentenNewsletter'])) {
        include('inc/fun_kunde.php');
        $query = mysql_query('select *, Kunde.ID as KundeID from kunde where abonnent = 1 and aktiv = 1');
        postKundenTabelle($query);

    } elseif (isset($_POST['sucheNewsletter'])) {
        
        
        $query = mysql_query('SELECT * from Newsletter where Betreff like "%' . $_POST['suche'] . '%" or Text like "%' . $_POST['suche'] . '%" order by ID asc');
        
        if (mysql_num_rows ($query) > 0) {
            echo '<div class="info">Suchergebnisse f&uuml;r "' . $_POST['suche'] . '"</div>';
        } else {
            echo '<div class="error">Keine Ergebnisse gefunden f&uuml;r "' . $_POST['suche'] . '"</div>';
        }

        postNewsletterTabelle ($query);
    } else {
        if (isset($_POST['aktivieren'])) {
            $aktiv = $_POST['aktivieren'];
            $query = mysql_query('UPDATE Newsletter set Aktiv="1" where ID="' . $aktiv . '"');
            if ($query) {
                // TODO: Fehlerbehandlung
            }
        }

        if (isset($_POST['deaktivieren'])) {
            $aktiv = $_POST['deaktivieren'];
            $query = mysql_query('UPDATE Newsletter set Aktiv="0" where ID="' . $aktiv . '"');
            if ($query) {
                // TODO: Fehlerbehandlung
            }
        }

        if (isset($_POST['aendernNewsletter'])) {
            $newsletter = $_POST['aendernNewsletter'];
            postNewsletterBearbeiten ($newsletter);
        } elseif (isset($_POST['resetid'])) {
            $newsletter = $_POST['resetid'];
            postNewsletterBearbeiten ($newsletter);
        } else {
            postNewsletterListe ();
        }
    }

    function postNewsletterListe () {
        

        $query = mysql_query("SELECT * from Newsletter order by ID asc");
        
        postNewsletterTabelle ($query);
    }

    function postNewsletterButtonLeiste () {
        echo '<div class="buttonleiste">';

        if (isset($_POST['neuerNewsletter']) || isset($_POST['aendernNewsletter']) || isset($_POST['resetid'])) {
            if (isset($_POST['aendernNewsletter'])) {
                $id = $_POST['aendernNewsletter'];
            } elseif (isset($_POST['resetid'])) {
                $id = $_POST['resetid'];
            }

            echo '<a href="index.php?section=newsletter"><button class="submit left r10" name="newsletter" type="submit">Zur Newsletter&uuml;bersicht</button></a>';
            echo '<form action="index.php?section=newsletter" method="post">
                    <input type="hidden" name="resetid" value="' . $id . '"> 
                    <button class="submit left r10">Reset</button>
                </form>';
            echo '<button class="submit left buttonIEdisable" name="speichernNewsletter" type="submit" form="newsletterform">Speichern</button>';
       
        } elseif (isset($_POST['detailsNewsletter'])) {
            $id = $_POST['detailsNewsletter'];

            $query = mysql_query('select * from newsletter where id = ' .$id);
            $newsletter = mysql_fetch_array($query);

            echo '<a href="index.php?section=newsletter"><button class="submit left r10" name="alleNewsletter" type="submit">Alle Newsletter anzeigen</button></a>';
            echo '<form action="index.php?section=newsletter" method="post">
                    <input type="hidden" name="aendernNewsletter" value="' . $id . '"> 
                    <button class="submit left r10">&Auml;ndern</button>
                </form>';
            echo '
                <form action="index.php?section=newsletter" method="post">
                    <input type="hidden" name="versendenNewsletter" value="' . $id . '">';
                        if ($newsletter['Aktiv'] == 0 && $newsletter['Sendedatum'] == null) {
                            echo '<button class="submit left" disabled>Versenden</button>';
                        } elseif ($newsletter['Sendedatum'] == null) {
                            echo '<button class="submit left">Versenden</button>';
                        } else {
                            echo '<button class="submit left">Versandt</button>';
                        }
                     echo '
                </form>';

        } elseif (isset($_POST['versendenNewsletter'])  || isset($_POST['abonnentenNewsletter'])) { 
            echo '<a href="index.php?section=newsletter"><button class="submit left r10" name="newsletter" type="submit">Zur Newsletter&uuml;bersicht</button></a>';

        } else {
            if (isset($_POST['sucheNewsletter'])) {
                echo '<a href="index.php?section=newsletter"><button class="submit left r10" name="alleNewsletter" type="submit">Alle Newsletter anzeigen</button></a>';
            } 

            echo '<form method="post" action="index.php?section=newsletter" class="left r10">
                <button class="submit r10" name="neuerNewsletter" type="submit">Newsletter hinzuf&uuml;gen</button>';
                if(!isset($_POST['sucheNewsletter'])){
                    echo '<button class="submit r10" name="abonnentenNewsletter" type="submit">Abonnenten anzeigen</button>';
                }

            echo' </form>';   

            echo '<a href="index.php?section=menu"><button class="submit left r10" name="menu" type="submit">Zum Men&uuml;</button></a>';

            echo '<form method="post" action="index.php?section=newsletter" id="searchNewsletter" class="right">
                <input class="suche" name="suche" placeholder="Suche" pattern=".+" type="search" />
                <button class="submit" name="sucheNewsletter" type="submit">Suche</button>
            </form>';
        }
        echo '</div>';
    }

    function postNewsletterTabelle ($query) {
        echo '<table class="liste clear">
            <tr>
                <th>#</th>
                <th>Betreff</th>
                <th>Sendedatum</th>
                <th>Versenden</th>
                <th>Status</th>
                <th>&Auml;ndern</th>
            </tr>';
        for ($i=0; $i < mysql_num_rows ($query); $i++) { 
            $newsletter = mysql_fetch_array($query);
            if ($i % 2 == 0) {
                echo '<tr>';
            } else {
                echo '<tr class="farbigeZeile">';
            }

            echo '<td>
                        <form action="index.php?section=newsletter" method="post">
                            <input type="hidden" name="detailsNewsletter" value="' . $newsletter['ID'] . '"> 
                            <button class="linkbutton">' . $newsletter['ID'] . '</button>
                        </form>
                    </td>';
            echo '
                        <td>' . $newsletter['Betreff'] . '</td>
                        <td>' . $newsletter['Sendedatum'] . '</td>';


            echo '
                <td>
                    <form action="index.php?section=newsletter" method="post">
                        <input type="hidden" name="versendenNewsletter" value="' . $newsletter['ID'] . '">';
                        if ($newsletter['Aktiv'] == 0 && $newsletter['Sendedatum'] == null) {
                            echo '<button class="linkbutton" disabled>Versenden</button>';
                        } elseif ($newsletter['Sendedatum'] == null) {
                            echo '<button class="linkbutton">Versenden</button>';
                        } else {
                            echo '<button class="linkbutton">Versandt</button>';
                        }
                     echo '</form>
                </td>';

            if ($newsletter['Aktiv'] == '1') {
                echo '
                    <td>
                        <form action="index.php?section=newsletter" method="post">
                            <input type="hidden" name="deaktivieren" value="' . $newsletter['ID'] . '"> 
                            <button class="linkbutton">Deaktivieren</button>
                        </form>
                    </td>';
            } else {
                echo '
                    <td>
                        <form action="index.php?section=newsletter" method="post">
                            <input type="hidden" name="aktivieren" value="' . $newsletter['ID'] . '"> 
                            <button class="linkbutton">Aktivieren</button>
                        </form>
                    </td>';
            }  

            echo '
                    <td>
                        <form action="index.php?section=newsletter" method="post">
                            <input type="hidden" name="aendernNewsletter" value="' . $newsletter['ID'] . '"> 
                            <button class="linkbutton">&Auml;ndern</button>
                        </form>
                    </td>
                </tr>';
        }
        echo '</table>';
    }

    function postNewsletterBearbeiten ($newsletter) {
        $query = mysql_query("SELECT * from Newsletter where ID=" . $newsletter);
        $row = mysql_fetch_array($query);
        postNewsletter($row);
    }

    function postNewsletter ($newsletter) {
        

        echo '
            <form class="formular" action="index.php?section=newsletter" method="post" id="newsletterform" name="newsletterform">
            <ul>
                <li>
                     <h2>Newsletter ';
            if (isset($newsletter['ID'])) {
                echo '#' . $newsletter['ID'] . ' &auml;ndern';
            } else {
                echo 'hinzuf&uuml;gen';
            }
                        
            echo '</h2>
                     <span class="required_notification">* Ben&ouml;tigte Felder</span>
                </li>
                <li>
                    <label for="betreff">Betreff:</label>
                    <input id="betreff" name="betreff" value="' . $newsletter['Betreff'] . '" type="text" placeholder="Betreff" maxlength="100" required />
                </li>
                <li>
                    <label for="text">Text:</label>
                    <textarea id="text" class="scrollable" name="text" placeholder="Newslettertext eintragen" onkeyup="ersetzeDoubleQuotes();" onblur="ersetzeDoubleQuotes();" onmousemove="ersetzeDoubleQuotes();" required>' . $newsletter['Text'] . '</textarea>
                </li>
                <li>
                    <label for="aktiv">Aktiv:</label>
                    <select id="aktiv" name="aktiv" size="1" required>
                        <option></option>';
        if ($newsletter['Aktiv'] == 0) {
            echo '<option value="' . 0 . '" selected="selected">Nein</option>';
        } else {
            echo '<option value="' . 0 . '">Nein</option>';
        }
        if ($newsletter['Aktiv'] == 1 || !isset($newsletter['Aktiv'])) {
            echo '<option value="' . 1 . '" selected="selected">Ja</option>';
        } else {
            echo '<option value="' . 1 . '">Ja</option>';
        }
        echo '
                    </select>
                    <input type="hidden" name="id" value="' . $newsletter['ID'] . '"> 
                </li>
                <li>
                    <button class="submit buttonIEenable" name="speichernNewsletter" type="submit">Speichern</button>
                </li>
            </ul>
        </form>
        ';
    }

    function postDetailsNewsletter ($newsletter) {

        $query = mysql_query("SELECT * from Newsletter where ID=" . $newsletter);
        $newsletter = mysql_fetch_array($query);
        

        echo '
        <table class="detailliste">
            <tr>
                <td colspan="2"><h2>Newsletter "' . $newsletter['Betreff'] . '"</h2></td>
            </tr>
            <tr>
                <td class="beschriftung">Betreff:</td>
                <td>' . $newsletter['Betreff'] . '</td>
            </tr>
            <tr>
                <td class="beschriftung">Text:</td>
                <td>' . $newsletter['Text'] . '</td>
            </tr>
            <tr>
                <td class="beschriftung">Sendedatum:</td>
                <td>' . $newsletter['Sendedatum'] . '</td>
            </tr>
            <tr>
                <td class="beschriftung">Aktiv:</td>';
            if ($newsletter['Aktiv'] == 1) {
                echo '<td>Ja</td>';
            } else {
                echo '<td>Nein</td>';
            }
            echo'</tr>
        </table>';
    }

    function sendNewsletter ($newsletter) {
        include ('lib/PHPMailer-master/class.phpmailer.php');

        $querykunde = mysql_query('SELECT * from kunde where abonnent = 1 and aktiv = 1 order by id');
        $querynewsletter = mysql_query('SELECT * from newsletter where id = ' . $newsletter);
        $newsletter = mysql_fetch_array($querynewsletter);

        if($newsletter['Sendedatum'] != null) {
            echo '<div class="error">Dieser Newsletter wurde bereits versandt.</div>';
            return;
        }

        if (mysql_num_rows($querykunde) == 0) {
            echo '<div class="error">Es sind keine Abonnenten vorhanden.</div>';
            return;
        }


        $mail = new PHPMailer;

        $mail->IsSMTP();                                      // Set mailer to use SMTP
        $mail->Host = 'mail.gmx.net';  // Specify main and backup server
        $mail->SMTPAuth = true;                               // Enable SMTP authentication
        $mail->Username = '165209673';                            // SMTP username
        $mail->Password = 'martin-hifi';                           // SMTP password
        $mail->SMTPSecure = 'SSL';                            // Enable encryption, 'ssl' also accepted
        
        $mail->From = 'martin-hifi@gmx.at';
        $mail->FromName = 'Felix-Martin-Hifi';
        $mail->WordWrap = 50;                                 // Set word wrap to 50 characters
        $mail->IsHTML(true);                                  // Set email format to HTML
        
        $mail->Subject = $newsletter['Betreff'];

        for($i=0; $i < mysql_num_rows($querykunde); $i++){
            if ($i==0) {
                echo '<div><h2>Der Newsletter "' . $newsletter['Betreff'] . ' " wurde an folgende Kunden versandt:</h2></div>
                <table class="detailliste">
                <tr>
                    <th>Kunde</th>
                    <th class="w100">Status</th>
                </tr>';
            }
            $kunde = mysql_fetch_array($querykunde);

            if($kunde['Anrede'] == "Herr") {
                $text = 'Sehr geehrter Herr ' . $kunde['Vorname'] . ' ' . $kunde['Nachname'] . '!</br></br>' . $newsletter['Text'];
            } elseif ($kunde['Anrede'] == "Frau") {
                $text = 'Sehr geehrte Frau ' . $kunde['Vorname'] . ' ' . $kunde['Nachname'] . '!</br></br>' . $newsletter['Text'];
            } else {
                $text = 'Sehr geehrte Damen und Herren!</br></br>' . $newsletter['Text'];
            }
            $mail->Body = $text;
            $mail->AddAddress($kunde['EMail']);  // Add a recipient
            if(!$mail->Send()) {
                echo '
                <tr>';
                if ($kunde['Anrede'] == 'Firma') {
                    echo '<td>' . $kunde['Firma'] . '</td>
                    <td><div class="w100 error">Mail-Error: ' . $mail->ErrorInfo . '</div></td>';
                } else {
                    echo '<td>' . $kunde['Vorname'] . ' ' . $kunde['Nachname'] . '</td>
                        <td><div class="w100 error">Mail-Error: ' . $mail->ErrorInfo . '</div></td>';
                }
                echo '</tr>';
            } else {
                echo '
                <tr>';
                if ($kunde['Anrede'] == 'Firma') {
                    echo '<td>' . $kunde['Firma'] . '</td>
                    <td><div class="w100 info">Erfolgreich</div></td>';
                } else {
                    echo '<td>' . $kunde['Vorname'] . ' ' . $kunde['Nachname'] . '</td>
                        <td><div class="w100 info">Erfolgreich</div></td>';
                }
                echo '</tr>';
            }
            $mail->to = array();
            $query = mysql_query('INSERT into newsletterkunde values (' . $newsletter['ID'] . ', ' . $kunde['ID'] . ')');
        }

        $string = 'UPDATE newsletter set sendedatum="' . date("Y-m-d",time()) . '" where id=' . $newsletter['ID'];
        $query = mysql_query($string);

    }

?>